//
//  CRLocalDataMgr.m
//  ChatRoom
//
//  Created by lee han on 12/11/12.
//  Copyright (c) 2012 lee han. All rights reserved.
//

#import "CRLocalDataMgr.h"

static CRLocalDataMgr* g_localDataMgr = nil;

@interface CRLocalDataMgr (Private);

- (NSString*)getValue:(NSString*)key;
- (void)saveValue:(NSString*)value forKey:(NSString*)key;

@end

@implementation CRLocalDataMgr

+ (CRLocalDataMgr*)sharedInstance
{
    @synchronized(self)
    {
        if (g_localDataMgr == nil)
        {
            g_localDataMgr = [[CRLocalDataMgr alloc] init];
        }
    }
    
    return g_localDataMgr;
}

- (NSString*)getPhoneNumber
{
    return [self getValue:@"phone"];
}

- (void)savePhoneNumber:(NSString *)number
{
    [self saveValue:number forKey:@"phone"];
}

- (NSString*)getPwd
{
    return [self getValue:@"pwd"];
}

- (void)savePwd:(NSString *)pwd
{
    [self saveValue:pwd forKey:@"pwd"];
}

#pragma mark Private

- (NSString*)getValue:(NSString *)key
{
    if ([[NSFileManager defaultManager] fileExistsAtPath:configFile()])
    {
        NSDictionary *fileData = [NSDictionary dictionaryWithContentsOfFile:configFile()];
        NSString* value = [fileData objectForKey:key];
        if (value != nil)
        {
            return value;
        }
    }
    return nil;
}

- (void)saveValue:(NSString *)value forKey:(NSString *)key
{
    NSMutableDictionary* fileData;
    if ([[NSFileManager defaultManager] fileExistsAtPath:configFile()])
    {
        fileData = [NSMutableDictionary dictionaryWithContentsOfFile:configFile()];
    }
    else
    {
        fileData = [[NSMutableDictionary alloc] initWithCapacity:1];
    }
    [fileData setObject:value forKey:key];
    
    [fileData writeToFile:configFile() atomically:YES];
}

//end Private
@end
